import {getUserId} from "@/api"
import deepClone from "@/utils/deepClone"
import {removeStorage, setStorage} from "@/utils/localstoreage"
import {toLogin} from "@/utils/pageRedirect"
import Taro from "@tarojs/taro"
import {observable, action, computed} from "mobx"
import {createContext} from "react"

/**
 * 小程序整体状态管理
 *
 * @param {userInfo:AppStore.UserInfo}
 * @desc 管理用户信息
 *
 * @param {mynav:AppStore.CNav}
 * @desc 自定义状态栏的相关信息
 *
 * @param {home:AppStore.Home}
 * @desc 首页状态管理
 */

class App {
	@observable userInfo: AppStore.UserInfo = {
		jsCode: "",
		token: "",
		weichatId: "",
		userCode: "",
		userCompany: "",
		userCreateTime: "",
		userDesc: null,
		userEmail: "",
		userId: 0,
		userLastLogin: "",
		userName: "",
		userNearName: "",
		userPhone: "",
		userWeichatId: "",
		weiChatBindStatus: null
	}

	@observable defaultUserInfo: AppStore.UserInfo = {
		jsCode: "",
		token: "",
		weichatId: "",
		userCode: "",
		userCompany: "",
		userCreateTime: "",
		userDesc: null,
		userEmail: "",
		userId: 0,
		userLastLogin: "",
		userName: "",
		userNearName: "",
		userPhone: "",
		userWeichatId: "",
		weiChatBindStatus: null
	}

	/**有无登录 */
	@observable isLogin: boolean = false

	@action.bound
	changeIsLogin(bol: boolean) {
		this.isLogin = bol
	}

	/**给userInfo赋值，同时将数据缓存本地 */
	@action.bound
	setUserInfo(data: User.Info | string, code?: string) {
		if (typeof data !== "string" && data.userWeichatId) {
			for (const key in data) {
				const val = data[key]
				this.userInfo[key] = val
				setStorage(key, val, 24)
			}

			this.changeIsLogin(true)
		} else if (typeof data === "string") {
			this.removeStoreByUserInfo()
			this.userInfo.userWeichatId = data
			setStorage("userWeichatId", data)

			this.changeIsLogin(false)
		}

		/**存储用户免登码 */
		if (code) {
			this.userInfo.jsCode = code
			setStorage("jsCode", code)
		}
	}

	@action.bound
	removeStoreByUserInfo() {
		this.userInfo = deepClone(this.defaultUserInfo)
		Object.keys(this.userInfo).map(key => {
			removeStorage(key)
		})
	}

	/**登录 */
	@action.bound
	async login(option?: {cb?: Function}) {
		Taro.login()
			.then(wxLogin => {
				let code = wxLogin.code
				getUserId({code})
					.then(res => {
						let {data} = res
						this.setUserInfo(data, code)
						option?.cb && option.cb()
					})
					.catch(err => {
						if (err) {
							let {data, result, msg} = err
							Taro.showModal({
								title: "提示",
								content: "是否前往登录，登录后才可绑定设备，查看监测数据和其他操作",
								cancelText: "暂不登录",
								confirmText: "去登录",
								success: res => {
									if (res.confirm) {
										toLogin()
									}
								}
							})
							this.setUserInfo(data, code)
						}
					})
			})
			.catch(err => {
				Taro.showToast({
					title: "免登失败!",
					icon: "none"
				})
			})
	}

	/**自定义头部状态栏用 */
	@observable mynav: AppStore.CNav = {
		/**状态栏高度 */
		statuHeight: 44,
		/**头部导航栏高度 */
		titleHeight: 44
	}
	@computed get statusBarHeight(): number {
		return this.mynav.statuHeight + this.mynav.titleHeight || 88
	}
	@action.bound
	setMynav(val: number, key: keyof AppStore.CNav) {
		this.mynav[key] = val
	}
}

const appStore = createContext(new App())

export default appStore
